import * as Mongoose from 'mongoose';
import { Exceptions } from "./../kalend";
import * as Grid from 'gridfs-stream'
import * as fs from 'fs';
import * as Koa from 'koa';
import * as request from 'request';
import { readFileSync } from 'fs';
import http = require('http');

class gridfs {
    private gfs: Grid.Grid;

    public makesureGrid(){
        if(!this.gfs){ this.gfs = Grid(Mongoose.connection.db, Mongoose.mongo);  }
    }

    async  Imageupload(file: any, ctx: Koa.Context): Promise<http.IncomingMessage> {

        const path = file.path;
        var that = this;
        var promise = new Promise<http.IncomingMessage>(async resolve => {

            let writestream = that.gfs.createWriteStream({
                filename: file.name
            });
            request(path).pipe(writestream);
            writestream.on('close', (file: any) => {
                resolve(file);
            });




        });

        return promise;

    }



    //      /**
    //      * 图片上传
    //      * @param file {name:name2,path:uri}
    //      */
    // async Imageupload(file: any) {

    //         const path = file.path;
    //         const fileInfo: any = await new Promise((resolve, reject) => {
    //             let writestream = this.gfs.createWriteStream({
    //                 filename: file.name
    //             });
    //            // fs.createReadStream(path).pipe(writestream);
    //              request(path).pipe(writestream);
    //           // request(path).pipe(fs.createWriteStream('doodle.png'));
    //             writestream.on('close', (file: any) => {
    //                 resolve(file);
    //             });
    //         });
    //        // return fileInfo;
    //     }
    /*
   *图片数据获取
   *@param 
   */
    async getimg(res: Koa.Response, id: any): Promise<any> {

        var buffer: any;
        const filter = { _id: id };
        var a: any;
        const item: any = await new Promise((resolve, reject) => {
            this.gfs.findOne(filter, (err, item) => {

                if (err) {
                    reject(err);
                } else {
                    if (item) {

                        // this.gfs.files.find({filename:item.filename}).toArray(function(err,files){
                        // if(!err)
                        // {

                        var fs_write = fs.createWriteStream("files/" + "bb.png");
                        var readstream = this.gfs.createReadStream(filter);


                        //  a=readstream;
                        readstream.pipe(fs_write);

                        //    res.body = readstream;


                        fs_write.on("close", function () {




                        });

                        a = readFileSync("files/bb.png");

                        readstream.on("data", function (chunk: any) {
                            buffer = chunk;

                        })
                        readstream.on("end", function () {
                            //  res.body = a;
                            resolve(item);

                        })



                        // }

                        // })


                    } else {
                        throw Exceptions.noFound();
                    }
                }
            });
        });
        return {
            body: buffer,
            filename: item.filename
        }


    }





}

export const Gridfs = new gridfs();